﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using CafeOnline.MvcFramework.Web.Json;

namespace CafeOnline.MvcFramework.Grid {
    public class CallGrid : Grid {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="gridType">Type of grid</param>
        /// <param name="id">Id of grid</param>
        public CallGrid(string gridType, string id)
            : base(gridType, id) {
        }

        /// <summary>
        /// Gets or sets the CTX.
        /// </summary>
        /// <value>
        /// The CTX.
        /// </value>
        public string Ctx {
            get;
            set;
        }

        public override void Populate(SerializationContext context) {
            //TODO: add custom settings here
            base.Populate(context);
        }

        public void RefreshColumn() {
            // Refresh All Visible Column
            // If grid has Edit, Del column -> Re add them (because we remove them away)
            // And so that we must Populated them 
            var context = new SerializationContext();
            context.Add("GridID", GridID);
            if ((this._enableEditButtons.HasValue) && (this._enableEditButtons.Value)) {
                // Column Edit
                Column editColumn = new Column("edit").SetLabel("<a class='ui-icon ui-icon-pencil'></a>").SetWidth(25).SetFixed(true).SetSortable(false).SetSearch(false).SetCustomFormatter(new CustomFormatter() {
                    Format = "function() {return \"<a class='ui-icon ui-icon-pencil editButton'></a>\";}"
                });
                editColumn.Populate(context);
                Columns.Add(editColumn);
            }
            if ((this._enableDeleteButtons.HasValue && this._enableDeleteButtons.Value)) {
                Column delColumn = new Column("Del").SetLabel("<a class='ui-icon ui-icon-trash'></a>").SetWidth(25).SetFixed(true).SetSortable(false).SetSearch(false).SetCustomFormatter(new CustomFormatter() {
                    Format = "function() {return \"<a class='ui-icon ui-icon-trash deleteButton'></a>\";}"
                });
                delColumn.Populate(context);
                Columns.Add(delColumn);
            }

            Columns.ForEach(t => t.Populate(context));
            this.Add("colModel", Columns.ToArray());
        }

        public override JavaScriptResult GetScript() {
            var script = new StringBuilder();

            string gridParam = String.Format("{0}DataGrid", GridID).Replace("-", "");
            script.AppendFormat("var {0} = {1};", gridParam, ToString());
            script.AppendLine("(function ($) { grid.init('#" + this.GridID + "', " + gridParam + "); })(this.jQuery);");
            // Search clear button
            if (this.SearchToolbar == true && this.SearchClearButton.HasValue && !string.IsNullOrWhiteSpace(this.Pager) && this.SearchClearButton.Value == true) {
                script.AppendFormat("$('#{0}').jqGrid('navGrid', '#{1}', { ", this.GridID, this.Pager).AppendLine();
                script.AppendLine("edit: false, ");
                script.AppendLine("add: false, ");
                script.AppendLine("del: false, ");
                script.AppendLine("search: false, ");
                script.AppendLine("refresh: true ");
                script.AppendLine("});");
                script.AppendFormat("$('#{0}').jqGrid('navButtonAdd', '#{1}', { ", this.GridID, this.Pager).AppendLine();
                script.AppendLine("caption: 'Clear', ");
                script.AppendLine("title: 'Clear Search', ");
                script.AppendLine("buttonicon: 'ui-icon-refresh', ");
                script.AppendLine("onClickButton: function() { ");
                script.AppendLine("mygrid[0].clearToolbar(); } ");
                script.AppendLine("});");
            }

            // Search toolbar
            if (this.SearchToolbar == true) {
                script.Append("$('#" + this.GridID + "').jqGrid('filterToolbar', { stringResult:true");

                if (_dataType == DataType.jsonstring || _dataType == DataType.local) {
                    script.Append(", defaultSearch: 'cn'");
                }
                if (this.SearchOnEnter.HasValue) {
                    script.AppendFormat(", searchOnEnter:{0}", this.SearchOnEnter.Value.ToString().ToLower()).AppendLine();
                }
                script.AppendLine(" });");
            }

            // Hide Column Headers Row
            if (this.HideColumnHeaders == true) {
                script.AppendLine("$('.ui-jqgrid-labels').hide();");
            }

            if (this._toolbar == true) {
                script.AppendFormat("$('#t_{0}').hide();", this.GridID);
            }

            // remove pointer cursor from non sortable columns
            script.AppendFormat("var cm = $('#{0}').jqGrid ('getGridParam', 'colModel');", this.GridID);
            script.AppendLine("if ($('#" + this.GridID + "').length > 0)");
            script.AppendLine("$.each($('#" + this.GridID + "')[0].grid.headers, function(index, value) {");
            script.AppendLine("var cmi = cm[index], colName = cmi.name;");
            script.AppendLine("if(!cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {");
            script.AppendLine("$('div.ui-jqgrid-sortable',value.el).css({cursor:'default'});");
            script.AppendLine("}");
            script.AppendLine("});");

            var res = new JavaScriptResult { Script = script.ToString() };
            return res;
        }

        /// <summary>
        /// Creates and returns javascript + required html elements to render grid
        /// </summary>
        /// <returns></returns>
        public override string ToHtmlString() {
            // Create javascript
            var script = new StringBuilder();
            script.AppendLine("<script type=\"text/javascript\">");
            script.AppendLine("$(document).ready(function () {");
            script.Append(GetScript().Script);
            script.AppendLine("});");
            script.AppendLine("</script>");

            // Create table which is used to render grid
            var html = new StringBuilder();
            html.AppendFormat("<table id=\"{0}\"></table>", this.GridID);

            // Create pager element if is set
            if (!string.IsNullOrWhiteSpace(this.Pager)) {
                html.AppendFormat("<div id=\"{0}\"></div>", this.Pager);
            }

            // Create grid title with tools
            if (!string.IsNullOrEmpty(this.Caption)) {
                var innerDiv = new StringBuilder();
                innerDiv.AppendFormat("<div id=\"{0}Div\">", this.GridID);

                if (this._toolbar == true) {
                    innerDiv.AppendLine("<ul class=\"pageTools\">");
                    innerDiv.AppendFormat("<li><a id=\"printcmd{2}\" class=\"print\" href=\"{1}\">{0}</a></li>", Localization.Resources.Print, VirtualPathUtility.ToAbsolute(String.Format("~/Grid/Print/?gridType={0}&gridID={1}",
                                                            GridType, GridID)), this.GridID);
                    innerDiv.AppendFormat("<li><a id=\"exportExcel{2}\" class=\"export\" href=\"{1}\">{0}</a></li>", Localization.Resources.Export, VirtualPathUtility.ToAbsolute(String.Format("~/Grid/ToExcel/?gridType={0}&gridID={1}",
                                                            GridType, GridID)), this.GridID);
                    innerDiv.AppendFormat("<li><a class=\"columSelector\" onclick=\"GetColumnSelector('{3}','{1}','{2}');\" href=\"#\">{0}</a></li>", Localization.Resources.SelectColumns, GridType, GridID, VirtualPathUtility.ToAbsolute(String.Format("~/Grid/GetColumnSelector")));
                    innerDiv.AppendLine("</ul>");
                }

                //innerDiv.AppendFormat("<h3>{0}<span class=\"notify\"><span class=\"wrap wrapNotify_{2}\">{1}</span></span></h3><span class=\"loader\"></span>", this.Caption, 0, this.GridID);
                innerDiv.Append(html.ToString());
                innerDiv.AppendLine("</div>");
                html = innerDiv;
            }

            // Return script + required elements
            return script.ToString() + html.ToString();
        }
    }
}
